<?php

namespace app\common\library\xiluhouse;

use OSS\OssClient;
use OSS\Core\OssException;
use app\common\exception\UploadException;
use think\File;

class Upload
{
    protected $_error = '';
    // 上传
    public function upload($file,$base64file='')
    {
        if($base64file&&empty($file)){
            if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64file, $result)){
                $type = $result[2];
                #上传文件后缀限制
                //$mimetype = config('upload.mimetype') ? explode(',',config('upload.mimetype')) : ["jpg","png","bmp","jpeg","gif","jpeg"];
                $mimetype =  ["jpg","png","bmp","jpeg","gif","jpeg"];
                if(!in_array($type,$mimetype)){
                    throw new UploadException(__('Uploaded file format is limited'));
                }
                $new_file = RUNTIME_PATH . 'img'. DS ;
                if(!file_exists($new_file))
                {
                    //检查是否有该文件夹，如果没有就创建，并给予最高权限
                    mkdir($new_file, 0700);
                }
                $filename=time().".{$type}";
                $new_file = $new_file.$filename;
                file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64file)));

                // 判断是否为
                $file = new File($new_file);
                $info = [
                    'name'     => $filename,
                    'type'     => $file->getMime(),
                    'tmp_name' => $new_file,
                    'error'    => 0,
                    'size'     => $file->getSize()
                ];
                $file->setSaveName($filename)->setUploadInfo($info);
                $file->isTest(true);
                $fileInfo = $file->getInfo();
            }
        }
        

        $uploadconfig = \think\Config::get('upload');
        $returndata = [];
        switch ($uploadconfig['storage']) {
            case 'local':
                # 本地上传
                $attachment = null;
                //默认普通上传文件
                try {
                    $upload = new \app\common\library\Upload($file);
                    $attachment = $upload->upload();
                } catch (UploadException $e) {
                    $this->setError($e->getMessage());
                    return false;
                }
                $returndata = ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)];
                break;
            case 'alioss':
                # 阿里oss
                return $this->ossupload($file);
                break;
            default:
                $this->setError('其他上传类型，请单独配置');
                return false;
                break;
        }
        return $returndata;
    }
    /**
     * oss上传代码
     */
    public function ossupload($file)
    {
        $config = get_addon_config('alioss');
        $oss = new OssClient($config['accessKeyId'], $config['accessKeySecret'], $config['endpoint']);
        $attachment = null;
        try {
            $upload = new \app\common\library\Upload($file);
            $attachment = $upload->upload();
        } catch (UploadException $e) {
            $this->setError($e->getMessage());
            return false;
        }

        //文件绝对路径
        $filePath = $upload->getFile()->getRealPath() ?: $upload->getFile()->getPathname();

        $url = $attachment->url;

        try {
            $ret = $oss->uploadFile($config['bucket'], ltrim($attachment->url, "/"), $filePath);
            //成功不做任何操作
        } catch (\Exception $e) {
            @unlink($filePath);
            $this->setError("上传失败" . $e->getMessage());
            return false;
        }
        @unlink($filePath);
        return ['url' => $url, 'fullurl' => cdnurl($url, true)];
    }
    /**
     * 设置错误信息
     *
     * @param string $error 错误信息
     * @return Auth
     */
    public function setError($error)
    {
        $this->_error = $error;
        return $this;
    }

    /**
     * 获取错误信息
     * @return string
     */
    public function getError()
    {
        return $this->_error ? __($this->_error) : '';
    }
}
